package com.fiveGroup.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fiveGroup.mapper.MessageMapper;
import com.fiveGroup.pojo.Message;
import com.fiveGroup.pojo.vo.PageResponseVo;
import com.fiveGroup.service.MessageService;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class MessageServiceImpl extends ServiceImpl<MessageMapper, Message> implements MessageService {

    @Autowired
    private MessageMapper messageMapper;

    @Override
    public List<Message> getChatHistory(Integer userId1, Integer userId2) {
        // 参数验证
        if (userId1 == null || userId2 == null) {
            log.warn("用户ID参数为空");
            return new ArrayList<>();
        }

        // 强制清除 PageHelper 的分页参数
        PageHelper.clearPage();

        List<Message> messages = messageMapper.selectChatHistory(userId1, userId2);
        return messages;
    }

    @Override
    public void markAsRead(Integer senderId, Integer receiverId) {
        messageMapper.markAsRead(senderId, receiverId);
    }

    @Override
    public Integer getUnreadCount(Integer receiverId) {
        return messageMapper.countUnreadMessages(receiverId);
    }

    // 你还可以重写 save 方法，加入发送 WebSocket 的逻辑
    @Override
    public boolean save(Message message) {
        boolean result = super.save(message); // 先保存到数据库

        if (result) {
            // 【重要】消息保存成功后，通过 WebSocket 推送给接收方
            // 这里假设你有一个 WebSocket 服务
            // WebSocketServer.sendToUser(message.getReceiverId(), message);
            System.out.println("消息已保存，准备推送...");
        }

        return result;
    }

    @Override
    public List<Integer> getFriends(Integer userId) {
        return messageMapper.getMutualFriends(userId);
    }

    //后台管理
    @Override
    public PageResponseVo<Message> getAllMessages(Integer senderId, Integer receiverId, String msgType, Integer currentPage, Integer pageSize) {
        Page<Message> page = new Page<>(currentPage, pageSize);
        LambdaQueryWrapper<Message> queryWrapper = new LambdaQueryWrapper<>();
        if (senderId != null) {
            queryWrapper.eq(Message::getSenderId, senderId);
        }
        if (receiverId != null) {
            queryWrapper.eq(Message::getReceiverId, receiverId);
        }
        if (msgType != null && !msgType.isEmpty()) {
            queryWrapper.eq(Message::getMsgType, msgType);
        }
        Page<Message> messagePage = messageMapper.selectPage(page, queryWrapper);
        return PageResponseVo.success(messagePage.getRecords(), messagePage.getTotal());
    }

    @Override
    public boolean editMessage(Long id, String content) {
        Message message = getById(id);
        if (message == null) {
            return false;
        }
        message.setContent(content);
        return updateById(message);
    }

    @Override
    public boolean deleteMessage(Long id) {
        return removeById(id);
    }

    @Override
    public boolean markAsRead(Long id) {
        Message message = getById(id);
        if (message == null) {
            return false;
        }
        message.setReadStatus(1);
        return updateById(message);
    }

    @Override
    public boolean batchDeleteMessages(List<Long> ids) {
        return removeByIds(ids);
    }

    @Override
    public boolean batchMarkAsRead(List<Long> ids) {
        return updateBatchById(ids.stream().map(id -> {
            Message message = new Message();
            message.setId(id);
            message.setReadStatus(1);
            return message;
        }).toList());
    }

//    @PostConstruct
//    public void debugTest() {
//        System.out.println("=== 启动时调试：查询用户18的好友 ===");
//        List<Integer> friends = messageMapper.getMutualFriends(18);
//        System.out.println("查到的好友ID列表: " + friends);
//    }
}

